package com.atguigu.schedule.filter;

import com.atguigu.schedule.pojo.SysUser;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

/**
 * @author yuezi2048
 * @version 1.0
 */
// servletNames也可以，是servlet注解中定义name属性即可
// 注意，这里登录过滤器可能会拦截跨域过滤器的预检请求，因此暂时关闭该过滤器，后续再改善
// @WebFilter(urlPatterns = {"/showSchedule.html", "/schedule/*"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获得Session域对象（通过Http子接口获取）
        HttpSession session = request.getSession();
        // 从Session域中获得用户对象
        SysUser sysUser = (SysUser) session.getAttribute("sysUser");

        // 判断是否为空，如果为空，回到login.html，否则正常放行
        if (null == sysUser) {
            response.sendRedirect("/login.html");
        } else {
            filterChain.doFilter(request, response);
        }

    }
}
